package com.fabric.contract;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

import java.net.ServerSocket;

@Component
public class DynamicPortConfig implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    private static final int DEFAULT_PORT = 8080;

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        int availablePort = findAvailablePort(DEFAULT_PORT);
        factory.setPort(availablePort);
        System.out.println("✅ 应用启动端口: " + availablePort);
    }

    private int findAvailablePort(int startingPort) {
        int port = startingPort;
        while (port < 65535) {
            try (ServerSocket socket = new ServerSocket(port)) {
                return port;  // 找到了未占用的端口
            } catch (Exception e) {
                port++;  // 尝试下一个
            }
        }
        throw new IllegalStateException("❌ 没有找到可用端口！");
    }
}
